declare namespace control {
    //% shim=control::programList
    function programList(): string[];
    //% shim=control::runProgram
    function runProgram(prog: string): void;
}

const logo = img`
    ...................................................
    ...3...333...3...1...1.111.1.1.111.111.111.11..111.
    ..3.....3.....3..11.11.1.1.11..1...1...1.1.1.1.1...
    ..3..3333333..3..1.1.1.111.1.1.11..1...1.1.1.1.11..
    ..3..3333333..3..1...1.1.1.1.1.111.111.111.11..111.
    ..3..33333.3..3....................................
    .3...33333.....3..111..1111...111...111..111..1111.
    ..3..33333.3..3..1...1.1...1.1...1.1...1.1..1.1....
    ..3..3333333..3..1...1.1...1.1.....1...1.1..1.1....
    ..3..3333333..3..11111.1111..1.....11111.1..1.111..
    ..3...........3..1...1.1...1.1...1.1...1.1..1.1....
    ...3.........3...1...1.1...1..111..1...1.111..1111.
`
let menuelts: string[] = [];
let cursor = 0;
let offset = 0;

menuelts = control.programList()
menuelts = menuelts.filter(s => s && s[0] != ".")

cursor = 0
offset = 0

function move(dx: number) {
    let nc = cursor + dx
    if (nc < 0) nc = 0
    else if (nc >= menuelts.length) nc = 0
    if (nc - offset < 2) offset = nc - 2
    if (nc - offset > 5) offset = nc - 5
    if (offset < 0) offset = 0
    cursor = nc
}

function select() {
    control.runProgram(menuelts[cursor])
}

controller.B.onEvent(ControllerButtonEvent.Pressed, function () {
    move(1)
})
controller.B.onEvent(ControllerButtonEvent.Repeated, function () {
    move(1)
})


controller.A.onEvent(ControllerButtonEvent.Pressed, function () {
    select()
})

game.onPaint(function () {
    screen.fillRect(0, 0, 160, 20, 12)
    //screen.print("more games", 60, 3, 1, image.font5)
    //screen.print("at makecode.com!", 60, 12, 1, image.font5)
    screen.drawTransparentImage(logo, 4, 4)
    for (let i = 0; i < 9; ++i) {
        let e = menuelts[i + offset] || "";
        e = e.split('_').join(' ')
        e = e.split('-').join(' ')
        let y = 25 + i * 11
        if (i + offset == cursor) {
            screen.fillRect(0, y - 2, 160, 11, 5)
            screen.print(e, 10, y, 15)
        }
        else
            screen.print(e, 10, y, 1)
    }
})